#import "RNEditViewController.h"
#import "RNConstants.h"
#import "RNStore.h"
#import "NSManagedObjectContext+SRAdditions.h"

#pragma mark -
@interface RNEditViewController (RNEditViewControllerPrivateMethods)
-(void)hideEditItemViewAndChangeFirstResponderToSuperview:(BOOL)shouldChangeFirstResponder;
@end


#pragma mark -
@implementation RNEditViewController

@synthesize editingItem = editingItem_;
@synthesize titleField = titleField_;
@synthesize storesController = storesController_;
@synthesize aislesController = aislesController_;

-(void)awakeFromNib {
    NSWindow *window = [NSApp mainWindow];
    [window addObserver:self forKeyPath:@"firstResponder" options:NSKeyValueObservingOptionNew context:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(mainWindowResignedKey:) name:NSWindowDidResignKeyNotification object:window];
}

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if (![keyPath isEqualToString:@"firstResponder"])
        return;
    if (![self editingItem])
        return;
    NSView *firstResponder = (NSView *)[[NSApp mainWindow] firstResponder];
    if (!firstResponder || [firstResponder isKindOfClass:[NSWindow class]] || firstResponder == [[self view] superview])
        return;
    NSView *parent = [firstResponder superview];
    while (parent != nil) {
        if (parent == [self view])
            return;
        parent = [parent superview];
    }
    // First responder changed to view that isn't a subview of the edit item view - hide the edit view
    [self hideEditItemViewAndChangeFirstResponderToSuperview:NO];
}

-(void)mainWindowResignedKey:(NSNotification *)note {
    [self hideEditItemView];
}

- (BOOL)control:(NSControl *)control textView:(NSTextView *)textView doCommandBySelector:(SEL)command {
    if (command == @selector(cancelOperation:)) {
        [self hideEditItemView];
        return YES;
    }
    return NO;
}

-(CGFloat)preferredHeightForWidth:(CGFloat)aWidth {return 0.0f;}

-(IBAction)closeEditItemView:(id)sender {
    [self hideEditItemView];
}

-(void)hideEditItemViewAndChangeFirstResponderToSuperview:(BOOL)shouldChangeFirstResponder {
    id editItem = [self editingItem];
    if (!editItem)
        return;
    
    NSView *superview = [[self view] superview];
    NSWindow *window = [[self view] window];
    [[self view] removeFromSuperview];
    [self setEditingItem:nil];
    [[NSNotificationCenter defaultCenter] postNotificationName:RNEditItemViewDidHideNotification object:editItem];
    if (shouldChangeFirstResponder)
        [window makeFirstResponder:superview];
}

-(void)hideEditItemView {
    [self hideEditItemViewAndChangeFirstResponderToSuperview:YES];
}

+(NSSet *)keyPathsForValuesAffectingAisleStrings {
    return [NSSet setWithObjects:@"editingItem", @"editingItem.aisles", nil]; 
}

-(NSArray *)aisleStrings {
    if (![self editingItem])
        return nil;
    NSArray *allStores = [[self managedObjectContext] fetchObjectsForEntityName:RNEntityNameStore withPredicate:nil];
    allStores = [allStores sortedArrayUsingDescriptors:[self storesControllerSortDescriptors]];
//    NSInteger longestTitle = 0;
//    for (NSString *title in [allStores valueForKey:@"title"]) {
//        NSInteger titleLength = [title length];
//        if (titleLength > longestTitle)
//            longestTitle = titleLength;
//    }
    NSArray *itemAisles = [[[self editingItem] aisles] allObjects];
    NSArray *itemStores = [itemAisles valueForKey:@"store"];
    NSMutableArray *aisleStrings = [NSMutableArray arrayWithCapacity:[allStores count]];
    for (RNStore *currentStore in allStores) {
        NSInteger indexOfStore = [itemStores indexOfObject:currentStore];
        NSString *aisleString = indexOfStore == NSNotFound ? @"No Aisle Assigned" : [[itemAisles objectAtIndex:indexOfStore] title];
        NSString *currentString = [NSString stringWithFormat:@"%@:  %@", [currentStore title], aisleString];
        [aisleStrings addObject:currentString];
    }
    return aisleStrings;
}

-(NSArray *)storesControllerSortDescriptors {
    return [NSArray arrayWithObject:[[NSSortDescriptor alloc] initWithKey:@"title" ascending:YES]];
}

@end
